﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using SIMS.Shared.DTO;
using SIMS.SysManagementModule.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using SIMS.Common.Models;
using SIMS.Common.RestClient;
using Newtonsoft.Json;
using SIMS.Shared.Models;

namespace SIMS.SysManagementModule.ViewModels
{
    public class AddEditRoleViewModel : BindableBase,IDialogAware
    {
        private bool isAddEdit;

        public bool IsAddEdit
        {
            get { return isAddEdit; }
            set { SetProperty(ref isAddEdit, value); }
        }

        private bool isEditMenu;

        public bool IsEditMenu
        {
            get { return isEditMenu; }
            set { SetProperty(ref isEditMenu, value); }
        }

        private RoleDTO role;

        public RoleDTO Role
        {
            get { return role; }
            set { SetProperty(ref role, value); }
        }

        private List<MenuInfo> menus;

        public List<MenuInfo> Menus
        {
            get { return menus; }
            set { SetProperty(ref menus, value); }
        }

        private readonly HttpRestClient _httpClient;

        public AddEditRoleViewModel(HttpRestClient httpClient)
        {
            _httpClient = httpClient;
        }

        private DelegateCommand loadedCommand;

        public DelegateCommand LoadedCommand
        {
            get
            {
                if (loadedCommand == null)
                {
                    loadedCommand = new DelegateCommand(Loaded);
                }
                return loadedCommand;
            }
        }

        private void Loaded()
        {
            InitInfo();
        }

        private async void InitInfo()
        {
            Menus = new List<MenuInfo>();
            var pagingModel = await GetMenus();
            if (pagingModel != null)
            {
                var entities = pagingModel.Items;
                Menus.AddRange(entities.Select(r => new MenuInfo(r)));
                //加载用户已有的角色
                if (Role != null && Role.Id > 0)
                {
                    var roleMenus = await GetRoleMenus(Role.Id);
                    foreach (var entity in roleMenus.Items)
                    {
                        var r = this.Menus.FirstOrDefault(r => r.Id == entity.MenuId);
                        if (r != null)
                        {
                            r.IsChecked = true;
                        }
                    }
                }
            }
        }

        private async Task<PagingModel<RoleMenuDTO>?> GetRoleMenus(int? roleId) 
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["roleId"] = roleId;
          
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Get;
            request.Parameters = parameters;
            request.Route = Api.ROLE_GETROLEMENUS;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                var menus = JsonConvert.DeserializeObject<PagingModel<RoleMenuDTO>>(JsonConvert.SerializeObject(response.data));
                return menus;
            }
            return null;
        }

        private async Task<PagingModel<MenuDTO>?> GetMenus()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["menuName"] = null;
            parameters["pageNum"] = 1;
            parameters["pageSize"] = -1;

            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Get;
            request.Parameters = parameters;
            request.Route = Api.MENU_GETMENUS;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                var menus = JsonConvert.DeserializeObject<PagingModel<MenuDTO>>(JsonConvert.SerializeObject(response.data));
                return menus;
            }
            return null;
        }


        private DelegateCommand cancelCommand;

        public DelegateCommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new DelegateCommand(Cancel);
                }
                return cancelCommand;
            }
        }

        private void Cancel()
        {
            RequestClose?.Invoke((new DialogResult(ButtonResult.Cancel)));
        }

        private DelegateCommand saveCommand;

        public DelegateCommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new DelegateCommand(Save);
                }
                return saveCommand;
            }
        }

        private async void Save()
        {
            if (Role != null)
            {
                bool flag = false;
                if (Role.Id > 0)
                {
                    flag = await UpdateRole(Role);
                }
                else
                {
                    flag = await AddRole(Role);
                }
                if (flag)
                {
                    RequestClose?.Invoke((new DialogResult(ButtonResult.OK)));
                }
            }
        }

        private async Task<bool> AddRole(RoleDTO role)
        {
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Post;
            request.Parameters = role;
            request.Route = Api.ROLE_ADDROLE;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private async Task<bool> UpdateRole(RoleDTO course)
        {
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Put;
            request.Parameters = course;
            request.Route = Api.ROLE_UPDATEROLE;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private DelegateCommand doCommand;

        public DelegateCommand DoCommand
        {
            get
            {
                if (doCommand == null)
                {
                    doCommand = new DelegateCommand(Do);
                }
                return doCommand;
            }
        }

        private async void Do()
        {
            if (Role.Id < 1)
            {
                MessageBox.Show("用户尚未保存，不可以授权");
                return;
            }
            var roleMenus = this.Menus.Where(r => r.IsChecked == true).ToList();
            if (roleMenus != null && roleMenus.Count() > 0)
            {
                var Ids = roleMenus.Select(r => r.Id);
                var strIds = string.Join(",", Ids);
                bool flag = await SetRoleMenus(Role.Id, strIds);
                if (flag)
                {
                    RequestClose?.Invoke((new DialogResult(ButtonResult.OK)));
                }
            }
            else
            {
                MessageBox.Show("必须至少分配一个菜单");
            }
        }

        private async Task<bool> SetRoleMenus(int? roleId, string menuIds)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["roleId"] = roleId;
            parameters["menuIds"] = menuIds;

            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Get;
            request.Parameters = parameters;
            request.Route = Api.ROLE_SETROLEMENUS;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        public string Title => "新增或编辑角色窗口";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters != null && parameters.ContainsKey("state"))
            {
                int state = parameters.GetValue<int>("state");
                if (state < 2)
                {
                    this.IsAddEdit = true;
                    this.IsEditMenu = false;
                }
                else
                {
                    this.IsAddEdit = false;
                    this.IsEditMenu = true;
                }
            }
            else
            {
                this.IsAddEdit = true;
                this.IsEditMenu = false;
            }

            if (parameters != null && parameters.ContainsKey("role"))
            {
                var role = parameters.GetValue<RoleDTO>("role");
                this.Role = (RoleDTO)role.Clone();
            }
            else
            {
                this.Role = new RoleDTO();
            }
        }
    }
}
